package com.weixing.mall.provider.support.excel;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.provider.model.domain.Goods;
import com.weixing.mall.provider.model.domain.GoodsImg;
import com.weixing.mall.provider.model.domain.GoodsIntro;
import com.weixing.mall.provider.model.query.CategoryQuery;
import com.weixing.mall.provider.model.query.GoodsQuery;
import com.weixing.mall.provider.model.vo.CategoryVo;
import com.weixing.mall.provider.model.vo.GoodsVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.util.ListUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TestImportDataListener extends AnalysisEventListener<TestImportData> {
    private static final Logger LOGGER = LoggerFactory.getLogger(TestImportData.class);
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IPhotoGalleryService photoGalleryService;
    @Autowired
    private IGoodsIntroService goodsIntroService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired

    private  IGoodsImgService goodsImgService;
    /**
     * 每隔500条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    List<TestImportData> list = new ArrayList<TestImportData>();
    List<CategoryVo> categoryVoList = Lists.newArrayList();
    List<GoodsVo> goodsList = Lists.newArrayList();


    public TestImportDataListener(IPhotoGalleryService photoGalleryService, IGoodsService goodsService, IGoodsIntroService goodsIntroService, ICategoryService categoryService, IGoodsImgService goodsImgService) {
        this.goodsService = goodsService;
        this.photoGalleryService = photoGalleryService;
        this.goodsIntroService = goodsIntroService;
        this.categoryService = categoryService;
        CategoryQuery categoryQuery = new CategoryQuery();
        categoryQuery.setIsEnable(WhetherEnum.YES.getValue());
        categoryQuery.setParentId(0L);
        categoryVoList = categoryService.selectList(categoryQuery);
        GoodsQuery query = new GoodsQuery();
        goodsList = goodsService.selectNoPage(query);
        this.goodsImgService=goodsImgService;
    }


    @Override
    public void invoke(TestImportData data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        List<DictTmp> dictTmpList = DictTmp.init();
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        List<GoodsIntro> goodsIntroList = Lists.newArrayList();
        List<Goods> goodsList1 = Lists.newArrayList();
        List<Goods> goodsList2 = Lists.newArrayList();
        List<GoodsImg> goodsImgs=Lists.newArrayList();
        for (TestImportData data : list) {
            if (null != data && null != data.getGoodsSn()) {
                GoodsVo checkGoodsVo = checkGoodSn(goodsList, data.getGoodsSn().replace("'", ""));
         /*
            Goods goods = new Goods();
            String goodsn = data.getGoodsSn();
            GoodsQuery query = new GoodsQuery();
            query.setGoodsSn(goodsn);

            if (null != checkGoodsVo) {
                GoodsVo goodsVo = goodsList.get(0);
                goods.setId(goodsVo.getId());
            }
            Goods entity = new Goods();
            BeanUtils.copyProperties(data, entity);
            entity.setStyleNo(data.getGoodsSn());
            String goodsSys = data.getGoodsSys();
            for (DictTmp tmp : dictTmpList) {
                if (tmp.getName().equals(goodsSys)) {
                    entity.setGoodsSys(tmp.getId() + "");//系列
                    break;
                }
            }
            String catergory = data.getCatName();
            for (CategoryVo categoryVo : categoryVoList) {
                if (categoryVo.getCatName().equals(catergory)) {
                    entity.setCatId(categoryVo.getId());
                    entity.setCatName(catergory);
                    break;
                }
            }
            String datatime = checkAndDataTime(data.getCreatedTime());
            try {
                entity.setCreatedTime(DateUtil.parse(datatime));
            } catch (Exception e) {
                String s1 = data.getCreatedTime();

            }
            String checktime = "2020-08-01 00:00:00";
            if (null != checkGoodsVo && (checkGoodsVo.getCreatedTime().getTime() - DateUtil.parse(checktime).getTime() < 0)) {
                if(checkGoodsVo.getGoodsSn().equals(data.getGoodsSn())){
                    entity.setGoodsSn(null);
                    entity.setStyleNo(null);
                }
                entity.setId(checkGoodsVo.getId());
                entity.setUpdatedTime(new Date());
                if(0!=entity.getId().longValue()){
                    goodsList1.add(entity);
                }

            } else if(null==checkGoodsVo) {
                entity.setStatus(2);
                entity.setIsHot(WhetherEnum.YES.getValue());
                entity.setExpressType(2);
                entity.setRevision(0);
                entity.setOrderNo(0L);
                entity.setGoodsFrom(3);
                entity.setGoodsType(1);
                entity.setCostPrice(new BigDecimal(0));
                goodsList2.add(entity);
            }
*/

                //Goods goods1=   goodsService.getOne(new QueryWrapper<Goods>().eq("goods_sn",data.getGoodsSn().trim()));
                // GoodsIntro goodsIntro= goodsIntroService.getOne(new QueryWrapper<GoodsIntro>().eq("goods_id",null==goods1?0L:goods1.getId()));
                if (null != checkGoodsVo) {
                    GoodsIntro entity = new GoodsIntro();
                    entity.setGoodsId(checkGoodsVo.getId());
                    StringBuffer buffer = new StringBuffer();
                    GoodsImg goodsImg = new GoodsImg();
                    goodsImg.setGoodsId(checkGoodsVo.getId());
                    String imag = data.getImage();
                    if (null != imag && !"".equals(imag)) {
                        String[] imagArray = imag.split(",");
                        buffer.append("<p>");
                        for (String ss : imagArray) {
                            if (ss.endsWith("jpg")) {
                                buffer.append("<img class=\"wscnph\" src=\"http://lmpic.weixingshishang.cn/" + ss + "\" />");
                            }
                        }
                        buffer.append("</p>");
                        if(imagArray.length!=0){
                            goodsImg.setGoodsImg(imagArray[0]);
                            entity.setGoodsIntro(buffer.toString());
                            entity.setCreatedBy(1L);
                            entity.setCreatedTime(new Date());
                            goodsIntroList.add(entity);
                            goodsImgs.add(goodsImg);
                        }

                    }


                }
            }
        }
        if(goodsIntroList.size()!=0){
            goodsIntroService.saveBatch(goodsIntroList, ListUtil.SIZE);
        }
        if(goodsImgs.size()!=0){
            goodsImgService.saveBatch(goodsImgs,ListUtil.SIZE);
        }
           /* if (goodsList1.size() != 0) {
                goodsService.updateBatchById(goodsList1);
            }
            if (goodsList2.size() != 0) {
                goodsService.saveBatch(goodsList2);
            }*/
            LOGGER.info("存储数据库成功！");

    }
    public  GoodsVo checkGoodSn(List<GoodsVo> goodsList, String goodsSn) {

        for (GoodsVo goodsVo : goodsList) {
            if (/*goodsVo.getGoodsSn().contains(goodsSn.trim())||goodsVo.getStyleNo().contains(goodsSn.trim())||*/goodsVo.getGoodsSn().equals(goodsSn.trim())/*||goodsVo.getStyleNo().equals(goodsSn.trim())*/) {
                return goodsVo;
            }
        }
        return null;
    }
   public  String checkAndDataTime(String time){

       String [] tt=time.split(" ");
       String [] t1=tt[0].split("-");
       String [] t2=tt[1].split(":");
       for(int i=0;i<t1.length;i++){
           if(t1[i].length()==1){
               t1[i]="0"+t1[i];
           }
       }
       for(int i=0;i<t2.length;i++){
           if(t2[i].length()==1){
               t2[i]="0"+t2[i];
           }
       }
       return  t1[0]+"-"+t1[1]+"-"+t1[2]+" "+t2[0]+":"+t2[1]+":"+t2[2];
   }
    public static void main(String[] args) {
        Date date=new Date();
        String checktime = "2020-08-01 00:00:00";
       Long id= date.getTime() - DateUtil.parse(checktime).getTime();
            System.out.println(id);
        }


}

class DictTmp {
    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    private Long id;
    private String name;

    public static List<DictTmp> init() {
        List<DictTmp> result = Lists.newArrayList();
        DictTmp t1 = new DictTmp();
        t1.setId(68L);
        t1.setName("时尚女装");
        DictTmp t2 = new DictTmp();
        t2.setId(69L);
        t2.setName("LMF系列");
        DictTmp t3 = new DictTmp();
        t3.setId(72L);
        t3.setName("优雅系列");
        DictTmp t4 = new DictTmp();
        t4.setId(73L);
        t4.setName("专柜女装");
        DictTmp t5 = new DictTmp();
        t5.setId(77L);
        t5.setName("专柜女装A");
        DictTmp t6 = new DictTmp();
        t6.setId(78L);
        t6.setName("意大利系列");
        DictTmp t7 = new DictTmp();
        t7.setId(83L);
        t7.setName("马夹");
        DictTmp t8 = new DictTmp();
        t8.setId(84L);
        t8.setName("男装");
        DictTmp t9 = new DictTmp();
        t9.setId(85L);
        t9.setName("其他");
        result.add(t1);
        result.add(t2);
        result.add(t3);
        result.add(t4);
        result.add(t5);
        result.add(t6);
        result.add(t7);
        result.add(t8);
        result.add(t9);
        return result;
    }
}